package com.tenement.controller.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.tenement.base.constants.SysmConstants.state;
import com.tenement.mybatis.entity.Photo;
import com.tenement.service.interfaces.IPhotoService;
import com.tenement.utils.ftp_images_server.FtpConfig;
import com.tenement.utils.ftp_images_server.FtpUtil;
import com.tenement.utils.ftp_images_server.UploadUtils;

/**
 * 批量上传图片和图片数据回写
 * 
 * @author wk
 *
 */
@Controller
public class UploadImageController {

	private static final Log logger = LogFactory.getLog(UploadImageController.class);

	@Autowired
	private IPhotoService iPhotoService;

	/**
	 * 数据上传
	 * 
	 * @param albumId
	 * @param files
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/uploadImages.action")
	public @ResponseBody String uploadFiles(@RequestParam("albumId") Integer albumId,
			@RequestParam("file") MultipartFile[] files) throws IOException {
		logger.info("【上传图片controller】");
		FtpConfig ftpConfig = new FtpConfig();
		List<Photo> photoList = new ArrayList<Photo>();

		for (MultipartFile file : files) {
			Photo photo = new Photo();
			String oldName = file.getOriginalFilename();// 获取图片原来的名字
			String picNewName = UploadUtils.generateRandonFileName(oldName);// 通过工具类产生新图片名称，防止重名
			String picSavePath = UploadUtils.generateRandomDir(picNewName);// 通过工具类把图片目录分级
			/*
			 * photo.setPhotoUrl(picSavePath + "/");//
			 * 设置图片的url--》就是存储到数据库的字符串url photo.setAlbumId(albumId);//
			 * 设置图片所属相册id photo.setUser_id("wk");
			 * photo.setPhoteName(picNewName);
			 */
			photoList.add(photo);
			FtpUtil.pictureUploadByConfig(ftpConfig, picNewName, picSavePath, file.getInputStream());// 上传到图片服务器的操作
			// 添加到数据库
		}
		iPhotoService.uploadImages(photoList);
		return state.Success;
	}
	

}
